import java.sql.*;
import java.util.ArrayList;

/**
 * Class to make the connection to the dataBase and 
 * write the data to the database
 * @author Marco Vellinga
 * @author Sander Wagenaar
 *
 */
public class ConnectDb {
	
	// Variable
	public ArrayList<Data> allData;
	Data data;
	public fillData fillData;
	
	/**
	 * Constructor
	 * @param data
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public ConnectDb(ArrayList<Data> allData) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
		
		this.allData = allData;
		connectToAndQueryDatabase();
	}
	
	/**
	 * Function to connect to the database and write data to the database
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public void connectToAndQueryDatabase() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		
		// Setting up the needed info for the connection
		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "unwdmi";
		String driver = "com.mysql.jdbc.Driver";
		String userName = "root"; 
		String password = "";
		
		try {
		  
			  // Setting up the connection
			  Class.forName(driver).newInstance();
			  conn = DriverManager.getConnection(url+dbName,userName,password);
			  
			  // Function to read all the data that 1 cluster send to the server
			  for(int i = 0; i < allData.size(); i++){
				  
			  data = allData.get(i);
			  // Query the database
			  Statement stmt = conn.createStatement();
			  stmt.executeUpdate("INSERT INTO data (stn,date,time,temp,dewp,stp," +
		    		"slp,visib,wdsp,prcp,sndp,frshtt,cldc,wnddir) VALUES ('" + data.getStn() + "','"
		    		+ data.getDate() + "','" + data.getTime() + "','" + data.getTemp() + "','" + data.getDewp() +
		    		"','" + data.getStp() + "','" + data.getSlp() + "','" + data.getVisib() + "','" 
		    		+ data.getWdsp() + "','" + data.getPrcp() + "','" + data.getSndp() + "','" +
		    		data.getFrshtt() + "','" + data.getCldc() + "','" + data.getWnddir() + "')");
		  
		  }
		// Close connection
		  conn.close();
		} catch(SQLException e){
			System.out.println(e);
		}	  
}
}
